package com.itmake.webflux.basic.util;

import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

public class WebfluxUtil {

    private WebfluxUtil(){}

    /**
     * 写出 webflux 模型响应
     *
     * @param response ServerHttpResponse
     * @param status http 状态码
     * @param value 响应内容
     * @return Mono<Void>
     */
    public static Mono<Void> resWrite(ServerHttpResponse response, HttpStatus status, Object value) {
        response.setStatusCode(status);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, ContentType.JSON.getValue());
        // 生成数据
        String res = JSONUtil.toJsonStr(value);
        // 写数据
        DataBuffer dataBuffer = response.bufferFactory().wrap(res.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(dataBuffer));
    }
}
